package mapx

import (
	"strings"
)

func ToMapInterface(st interface{}, val interface{}, args ...interface{}) (r interface{}) {
	r = copyAny(st, val, true)
	return
}

func ToMapStruct(st IToMap, val interface{}, args ...interface{}) {
	m, ok := val.(map[string]interface{})
	if ok == true {
		st.ToMap(m, args...)
	}
	return
}

func ToMapStructByType(val interface{}, args ...interface{}) (r interface{}) {

	toval, ok := val.(IToMap)
	if ok {
		m := map[string]interface{}{}
		toval.ToMap(m, args...)
		if stname, ok := toval.(IStructName); ok {
			m["_type"] = stname.StructName()
		}
		r = m
	} else {
		switch v := val.(type) {
		case []interface{}:
			r = copyArray(v, []interface{}{}, true)
		case map[string]interface{}:
			m := map[string]interface{}{}
			r = copyAny(v, m, true)
		default:
			r = v
		}
	}

	return
}

func ToMapAllStruct(st IToMapAll, val interface{}, args ...interface{}) {
	m, ok := val.(map[string]interface{})
	if ok == true {
		if st != nil {
			st.ToMapAll(m, args...)
		}
	}
	return
}

func CreateConfigMap2(keys []string, r map[string]interface{}, val interface{}) {
	cur := r
	l := len(keys)
	for i := 0; i < l; i++ {
		k := keys[i]
		if i != l-1 {
			a := map[string]interface{}{}
			cur[k] = a
			cur = a
		} else {
			cur[k] = val
		}
	}

	return
}

func CreateConfigMap3(keys string, r map[string]interface{}, val interface{}) {
	arrs := strings.Split(keys, ".")

	cur := r
	l := len(arrs)
	for i := 0; i < l; i++ {
		k := arrs[i]
		if i != l-1 {
			a := map[string]interface{}{}
			cur[k] = a
			cur = a
		} else {
			cur[k] = val
		}
	}

	return
}
